<template>
  <div class="upload-container">
    <el-button icon='el-icon-upload' size="mini" :style="{background:color,borderColor:color}"
      @click=" dialogVisible=true" type="primary">发送图片
    </el-button>
    <el-dialog append-to-body :visible.sync="dialogVisible">
      <el-upload class="editor-slide-upload" :action="uploadURL" :http-request="onUpload" accept='image/jpeg,image/png' :show-file-list="false"
        list-type="picture-card" :on-success="handleSuccess" :before-upload="beforeUpload">
        <img v-if="imageUrl" :src="imageUrl" class="js-preview-image">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        <!-- <el-button v-else size="small" type="primary">选择图片</el-button> -->
      </el-upload>
      <el-button @click.stop="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click.stop="handleSubmit">发 送</el-button>
    </el-dialog>
  </div>
</template>

<script>
  import axios from 'axios';

  export default {
    name: 'editorSlideUpload',
    props: {
      color: {
        type: String,
        default: '#1890ff'
      }
    },
    data() {
      return {
        dialogVisible: false,
        imageUrl: '',
        // eslint-disable-next-line no-undef
        uploadURL: process.env.BASE_API + '/Chat/UploadImage'
      };
    },
    methods: {
      handleSubmit() {
        if(this.imageUrl){
          this.$emit('successCBK', this.imageUrl);
          this.imageUrl = '';
          this.dialogVisible = false;
        }
      },
      handleSuccess(response, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeUpload(file) {
        const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt10M = file.size / 1024 / 1024 < 10;

        if (!isImage) {
          this.$message.error('上传头像图片只能是 JPG 或者 PNG 格式!');
        }
        if (!isLt10M) {
          this.$message.error('上传图片大小不能超过 10MB!');
        }
        return isImage && isLt10M;
      },
      dataURItoBlob(dataURI, type) {
        var binary = atob(dataURI.split(',')[1]);
        var array = [];
        for(var i = 0; i < binary.length; i++) {
          array.push(binary.charCodeAt(i));
        }
        return new Blob([new Uint8Array(array)], {type: type});
      },
      onUpload(param){
        this.imgPreview(param.file);
      },
      //获取图片
      imgPreview(file) {
        let self = this;
        //判断支不支持FileReader
        if (!file || !window.FileReader) return;
        if (/^image/.test(file.type)) {
          //创建一个reader
          let reader = new FileReader();

          //将图片转成base64格式
          reader.readAsDataURL(file);
          //读取成功后的回调
          reader.onloadend = function() {
            let result = this.result;
            let img = new Image();
            img.src = result;
            img.onload = function() {
              let data = self.compress(img);
              self.imgUrl = result;

              let blob = self.dataURItoBlob(data);

              var formData = new FormData();
              formData.append('image.jpg', blob);
              let config = {
                headers: { 'Content-Type': 'multipart/form-data' }
              };
              // 发送请求;
              // eslint-disable-next-line no-undef
              axios.post(self.uploadURL, formData, config).then(res => {
                if (res.data.code === 0) {
                  self.imageUrl = res.data.data;
                } else {
                  self.$toast('图片上传失败，请重试');
                }
              });
            };
          };
        }
      },
      // 压缩图片
      compress(img) {
        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');
        let width = img.width;
        let height = img.height;

        var maxWidth = 800,
          maxHeight = 800;
        // 目标尺寸
        var targetWidth = width,
          targetHeight = height;
        // 图片尺寸超过800 x 800的限制
        if (width > maxWidth || height > maxHeight) {
          if (width / height > maxWidth / maxHeight) {
            // 更宽，按照宽度限定尺寸
            targetWidth = maxWidth;
            targetHeight = Math.round(maxWidth * (height / width));
          } else {
            targetHeight = maxHeight;
            targetWidth = Math.round(maxHeight * (width / height));
          }
        }

        canvas.width = targetWidth;
        canvas.height = targetHeight;
        // 铺底色
        ctx.fillStyle = '#fff';

        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

        let ndata = canvas.toDataURL('image/jpeg', 1);
        //进行最小压缩
        var length = ndata.length;
        if(length > 200 * 1024){
          var compressRate = 0.9;
          if (length > 600 * 1024) {
            compressRate = 0.5;
          } else if (length > 400 * 1024) {
            compressRate = 0.7;
          }
          ndata = canvas.toDataURL('image/jpeg', compressRate);
        }
        return ndata;
      },
    }
  };

</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .editor-slide-upload {
    margin-bottom: 20px;

    /deep/ .el-upload--picture-card {
      width: 100%;
      height: 406px;
      line-height: 400px;
      text-align: center;
      vertical-align: middle;

      button {
        margin-top: 180px;
      }

      img {
        max-width: 400px;
        max-height: 400px;
      }
    }
  }

</style>
